package com.mostromas.ess.project.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mostromas.ess.entities.UpdateVersionInfo;
import com.mostromas.ess.project.mapper.UpdateVersionMapper;
import com.mostromas.ess.project.req.UpdateVersionREQ;
import com.mostromas.ess.project.service.IUpdateVersionService;
import com.mostromas.ess.util.base.Result;
import com.mostromas.ess.util.tools.CompareVersionUtil;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service
class UpdateVersionServiceImpl extends ServiceImpl<UpdateVersionMapper, UpdateVersionInfo> implements IUpdateVersionService {
    @Override
    public Result queryList(UpdateVersionREQ req) throws Exception {
        QueryWrapper<UpdateVersionInfo> wrapper = new QueryWrapper();
        if(req.getClientType() != null) {
            wrapper.eq("client_type", req.getClientType());
        }
        if(req.getName() != null) {
            wrapper.eq("name", req.getName());
        }
        wrapper.orderByAsc("client_type");
        wrapper.orderByAsc("version");
        return Result.ok(baseMapper.selectPage(req.getPage(),wrapper));
    }

    @Override
    public Result queryListByVersion(UpdateVersionREQ req) throws Exception {
        UpdateVersionInfo info = new UpdateVersionInfo();
        info.setUpdateVersions(getInfoByClientType(req));
        return Result.ok(info);
    }

    @Override
    public Result checkIsForcibly(UpdateVersionREQ req) throws Exception {
        List<UpdateVersionInfo> versionInfoList = getInfoByClientType(req);
        UpdateVersionInfo info = new UpdateVersionInfo();
        info.setClientType(req.getClientType());
        info.setUpdateVersions(versionInfoList);
        if(versionInfoList.size() > 0) {
            info.setIsForcibly(true);
        }else{
            info.setIsForcibly(false);
        }
        return Result.ok(info);
    }

    public List<UpdateVersionInfo> getInfoByClientType(UpdateVersionREQ req) throws Exception {
        QueryWrapper<UpdateVersionInfo> wrapper = new QueryWrapper();
        if(req.getClientType() != null) {
            wrapper.eq("client_type", req.getClientType());
        }
        if(req.getClientType() != null) {
            wrapper.eq("name", req.getName());
        }
        wrapper.orderByAsc("client_type");
        wrapper.orderByAsc("version");
        List<UpdateVersionInfo> versionInfoList = baseMapper.selectList(wrapper);
        Iterator<UpdateVersionInfo> iterator = versionInfoList.iterator();
        if(req.getVersion() != null){
            while (iterator.hasNext()){
                UpdateVersionInfo info = iterator.next();
                if(CompareVersionUtil.compareVersion(req.getVersion(),info.getVersion())>=0){
                    iterator.remove();
                }
            }
        }

        return versionInfoList;
    }
}
